package com.jungle.mvvm.update;

import android.text.TextUtils;

import com.xuexiang.xupdate.XUpdate;
import com.xuexiang.xupdate.entity.CheckVersionResult;
import com.xuexiang.xupdate.entity.UpdateEntity;
import com.xuexiang.xupdate.listener.IUpdateParseCallback;
import com.xuexiang.xupdate.proxy.IUpdateParser;
import com.xuexiang.xupdate.utils.UpdateUtils;

/**
 * @ClassName MyUpdateParser
 * @Description MyUpdateParser
 * @Author Daniel
 * @Version V1.0.0
 */
public class MyUpdateParser implements IUpdateParser {

    @Override
    public UpdateEntity parseJson(String json) throws Exception {
        if (!TextUtils.isEmpty(json)) {
            CheckVersionResult checkResult = (CheckVersionResult) UpdateUtils.fromJson(json, CheckVersionResult.class);
            if (checkResult != null && checkResult.getCode() == 0) {
                checkResult = this.doLocalCompare(checkResult);
                UpdateEntity updateEntity = new UpdateEntity();
                if (checkResult.getUpdateStatus() == 0) {
                    updateEntity.setHasUpdate(false);
                } else {
                    if (checkResult.getUpdateStatus() == 2) {
                        updateEntity.setForce(true);
                    }

                    updateEntity.setHasUpdate(true).setUpdateContent(checkResult.getModifyContent()).setVersionCode(checkResult.getVersionCode()).setVersionName(checkResult.getVersionName()).setDownloadUrl(checkResult.getDownloadUrl()).setSize(checkResult.getApkSize()).setMd5(checkResult.getApkMd5());
                    updateEntity.getDownLoadEntity().setShowNotification(true);
                }

                return updateEntity;
            }
        }

        return null;
    }

    @Override
    public void parseJson(String json, IUpdateParseCallback callback) throws Exception {

    }

    @Override
    public boolean isAsyncParser() {
        return false;
    }

    private CheckVersionResult doLocalCompare(CheckVersionResult checkResult) {
        if (checkResult.getUpdateStatus() != 0) {
            int lastVersionCode = checkResult.getVersionCode();
            if (lastVersionCode <= UpdateUtils.getVersionCode(XUpdate.getContext())) {
                checkResult.setRequireUpgrade(0);
            }
        }

        return checkResult;
    }
}
